import React, { Component } from "react";
import {
  Input,
  Row,
  Col,
  Form,
  DatePicker,
  Button,
  Table,
  Badge,
  Modal,
  message
} from "antd";
import { connect } from "dva";
import styles from "./MonitorPush.less";

const { RangePicker } = DatePicker;

const columns = [
  {
    title: "推送时间",
    dataIndex: "pushTime",
    sorter: true,
    defaultSortOrder: "descend"
  },
  {
    title: "应用编号",
    dataIndex: "dstAppId"
  },
  {
    title: "应用名称",
    dataIndex: "dstAppName"
  },
  {
    title: "状态",
    dataIndex: "isDeal",
    filters: [
      { text: "未调用", value: "false" },
      { text: "已调用", value: "true" }
    ],
    filterMultiple: false,
    // onFilter: (value, record) => record.isDeal.toString().indexOf(value) === 0,
    render: text => (
      <div>
        {text === "true" ? (
          <Badge status="processing" text="已调用" />
        ) : (
          <Badge status="default" text="未调用" />
        )}
        {/* <font>{text}</font> */}
      </div>
    )
    // width: "20%"
  },
  {
    title: "调用时间",
    dataIndex: "dealTime"
    // sorter: true
    // width: "20%"
  }
];

@connect(stores => ({
  moniPushData: stores.moniPush
}))
@Form.create()
class MonitorPush extends Component {
  state = {
    visible: false,
    pageIndex: 1,
    pageSize: 10,
    isDeal: [],
    order: "desc"
  };

  componentDidMount() {
    const { dispatch } = this.props;
    const { pageIndex, pageSize } = this.state;
    dispatch({
      type: "moniPush/getPushData",
      payload: {
        pageIndex,
        pageSize,
        appId: "sxbk",
        order: "desc"
      }
    });
  }

  handleSearch = e => {
    e.preventDefault();
    const params = {};
    this.props.form.validateFields((err, values) => {
      if (values.date) {
        // console.log(values.date.format("YYYY-MM-DD"));
        params.beginTime = values.date[0].format("YYYY-MM-DD HH:mm:ss");
        params.endTime = values.date[1].format("YYYY-MM-DD HH:mm:ss");
      }
      if (values.appName) {
        params.dstAppName = values.appName;
      }
    });
    const { dispatch } = this.props;
    const { pageSize, order, isDeal } = this.state;
    this.setState({ pageIndex: 1 });
    params.pageIndex = 1;
    params.pageSize = pageSize;
    params.appId = "sxbk";
    params.order = order;
    if (isDeal && isDeal.length === 1) {
      const a = isDeal[0];
      params.isDeal = a;
    }
    dispatch({
      type: "moniPush/getPushData",
      payload: params
    });
  };

  reset = () => {
    this.props.form.resetFields();
    const { dispatch } = this.props;
    const { pageSize } = this.state;
    this.setState(
      {
        pageIndex: 1
      },
      () => {
        const { pageIndex, order, isDeal } = this.state;
        const params = {
          pageIndex,
          pageSize,
          appId: "sxbk",
          order
        };
        if (isDeal && isDeal.length === 1) {
          const a = isDeal[0];
          params.isDeal = a;
        }
        dispatch({
          type: "moniPush/getPushData",
          payload: params
        });
      }
    );
  };

  showModal = () => {
    this.setState({
      visible: true
    });
  };

  handleOk = () => {
    const { dispatch } = this.props;
    dispatch({
      type: "moniPush/pushMsg"
    }).then(() => {
      const { moniPushData } = this.props;
      const { errCode, errMsg } = moniPushData;
      if (errCode === 0) {
        message.success("推送成功");
        const { pageSize, order, isDeal } = this.state;
        this.setState({
          pageIndex: 1
        });
        const params = {
          pageIndex: 1,
          pageSize,
          appId: "sxbk",
          order
        };
        if (isDeal && isDeal.length === 1) {
          const a = isDeal[0];
          params.isDeal = a;
        }
        dispatch({
          type: "moniPush/getPushData",
          payload: params
        });
      }
      if (errCode === "服务失败" && errMsg === "请勿重复发送") {
        Modal.info({
          title: "不可在半小时之内重复推送",
          onOk() {}
        });
      }
    });
    this.setState({
      visible: false
    });
  };

  handleCancel = () => {
    this.setState({
      visible: false
    });
  };

  handleTableChange = (e, filters, sorter) => {
    const { current, pageSize } = e;
    const { isDeal } = this.state;
    // console.log(e, filters, sorter);
    if (filters.isDeal && filters.isDeal.length === 1) {
      this.setState({
        pageIndex: filters.isDeal !== isDeal ? 1 : current,
        pageSize,
        order: sorter.order && sorter.order === "ascend" ? "asc" : "desc",
        isDeal: filters.isDeal
      });
      const { dispatch } = this.props;
      dispatch({
        type: "moniPush/getPushData",
        payload: {
          pageIndex: filters.isDeal !== isDeal ? 1 : current,
          pageSize,
          appId: "sxbk",
          order: sorter.order && sorter.order === "ascend" ? "asc" : "desc",
          isDeal: filters.isDeal[0]
        }
      });
    } else {
      this.setState({
        pageIndex: filters.isDeal && filters.isDeal !== isDeal ? 1 : current,
        pageSize,
        order: sorter.order && sorter.order === "ascend" ? "asc" : "desc",
        isDeal: filters.isDeal
      });
      const { dispatch } = this.props;
      dispatch({
        type: "moniPush/getPushData",
        payload: {
          pageIndex: filters.isDeal && filters.isDeal !== isDeal ? 1 : current,
          pageSize,
          appId: "sxbk",
          order: sorter.order && sorter.order === "ascend" ? "asc" : "desc"
        }
      });
    }
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    const { pageIndex } = this.state;
    const { moniPushData } = this.props;
    const { pushList = [], loading, totalCount } = moniPushData;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      }
    };
    return (
      <div className={styles.root}>
        <Modal
          title="布控推送"
          visible={this.state.visible}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
        >
          <p style={{ textAlign: "center" }}>是否推送布控消息给对接应用？</p>
        </Modal>
        <div className={styles.top}>
          <Form onSubmit={this.handleSearch}>
            <Row gutter={24}>
              <Col span={4} style={{ marginTop: 4, textAlign: "left" }}>
                <Button
                  type="primary"
                  onClick={this.showModal}
                  style={{ marginLeft: 24 }}
                >
                  布控推送
                </Button>
              </Col>
              <Col span={8} style={{ display: "inline" }}>
                <Form.Item label={`应用名称：`} {...formItemLayout}>
                  {getFieldDecorator(`appName`)(<Input placeholder="请输入" />)}
                </Form.Item>
              </Col>
              <Col span={8} style={{ display: "inline" }}>
                <Form.Item label={`推送时间：`} {...formItemLayout}>
                  {getFieldDecorator("date")(
                    <RangePicker style={{ width: "100%" }} showTime />
                  )}
                </Form.Item>
              </Col>
              <Col span={4} style={{ marginTop: 4, textAlign: "right" }}>
                <Button type="primary" htmlType="submit">
                  查询
                </Button>
                <Button
                  style={{ marginLeft: 8, marginRight: 24 }}
                  onClick={this.reset}
                >
                  重置
                </Button>
              </Col>
            </Row>
          </Form>
        </div>
        <div className={styles.btm}>
          <Table
            size="middle"
            columns={columns}
            // rowKey={record => record.login.uuid}
            dataSource={pushList}
            loading={loading}
            onChange={(e, filters, sorter) =>
              this.handleTableChange(e, filters, sorter)
            }
            locale={{ emptyText: "暂无数据！" }}
            pagination={{
              defaultPageSize: 10,
              showQuickJumper: true,
              showSizeChanger: true,
              current: pageIndex,
              total: totalCount,
              showTotal: total =>
                `共 ${total} 条记录 第${pageIndex}/${Math.ceil(total / 10)}页`
            }}
          />
        </div>
      </div>
    );
  }
}

export default MonitorPush;
